package service

import (
	"SimpleDockerPanel/controllers/service/models"
	"SimpleDockerPanel/dao"
	u "SimpleDockerPanel/pkg/utils"
	"errors"
)

func Register(name, password, email string) error {
	// 检查用户名是否已经存在
	user, _ := dao.GetUserByName(name)
	if user.Id != 0 {
		return errors.New("用户名已经存在")
	}
	// 检查邮箱是否已经存在
	user, _ = dao.GetUserByEmail(password)
	if user.Id != 0 {
		return errors.New("邮箱已经存在")
	}
	// 注册用户
	addUser, err := dao.InsertUser(name, password, email)
	if err != nil {
		return err
	}
	if addUser.Id == 0 {
		return errors.New("注册失败")
	}
	return nil
}

func Login(name, password string) (models.User, error) {
	user, _ := dao.GetUserByName(name)
	if user.Id == 0 {
		return models.User{}, errors.New("登录失败，用户名或密码错误")
	}
	if user.Password != u.EncryMd5(password) {
		return models.User{}, errors.New("登录失败，用户名或密码错误")
	}
	retUser := models.User{
		Id:       user.Id,
		Name:     user.Name,
		Password: user.Password,
		Email:    user.Email,
		GroupId:  user.GroupId,
	}

	return retUser, nil
}
